package com.fsh.subject.domain.service.impl;

import com.alibaba.fastjson.JSON;
import com.fsh.subject.common.entity.PageResult;
import com.fsh.subject.common.enums.IsDeletedFlagEnum;
import com.fsh.subject.common.util.IdWorkerUtil;
import com.fsh.subject.common.util.LoginUtil;
import com.fsh.subject.domain.convert.SubjectInfoConverter;
import com.fsh.subject.domain.entity.SubjectInfoBO;
import com.fsh.subject.domain.entity.SubjectOptionBO;
import com.fsh.subject.domain.handler.subject.SubjectTypeHandler;
import com.fsh.subject.domain.handler.subject.SubjectTypeHandlerFactory;
import com.fsh.subject.domain.reids.RedisUtil;
import com.fsh.subject.domain.service.SubjectInfoDomainService;
import com.fsh.subject.domain.service.SubjectLikedDomainService;
import com.fsh.subject.infra.basic.entity.SubjectInfo;
import com.fsh.subject.infra.basic.entity.SubjectInfoEs;
import com.fsh.subject.infra.basic.entity.SubjectLabel;
import com.fsh.subject.infra.basic.entity.SubjectMapping;
import com.fsh.subject.infra.basic.service.SubjectEsService;
import com.fsh.subject.infra.basic.service.SubjectInfoService;
import com.fsh.subject.infra.basic.service.SubjectLabelService;
import com.fsh.subject.infra.basic.service.SubjectMappingService;
import com.fsh.subject.infra.rpc.UserRpc;
import com.fsh.subject.infra.rpc.entity.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SubjectInfoDomainServiceImpl implements SubjectInfoDomainService {

    @Resource
    private SubjectInfoService subjectInfoService;
    @Resource
    private SubjectLabelService subjectLabelService;
    @Resource
    private SubjectTypeHandlerFactory subjectTypeHandlerFactory;
    @Resource
    private SubjectMappingService subjectMappingService;
    @Resource
    private SubjectEsService subjectEsService;
    @Resource
    private SubjectLikedDomainService subjectLikedDomainService;
    @Resource
    private UserRpc userRpc;
    @Resource
    private RedisUtil redisUtil;

    private static final String RANK_KEY = "subject_rank";

    /**
     * 新增题目
     *使用工厂+策略模式
     * @param subjectInfoBO 主题信息
     * @return {@link Boolean}
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean add(SubjectInfoBO subjectInfoBO) {
        if (log.isInfoEnabled()) {
            log.info("SubjectInfoDomainServiceImpl.add.bo:{}", JSON.toJSONString(subjectInfoBO));
        }
        //这里可以直接把题目的信息添加到 subject_info表
        SubjectInfo subjectInfo = SubjectInfoConverter.INSTANCE.convertBoToInfo(subjectInfoBO);
        subjectInfo.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        subjectInfoService.insert(subjectInfo);

        //这里判断题目的类型，分别插入不同的表格。
        //使用工厂+策略模式

        //根据 subjectType 来获取对应 的  SubjectTypeHandler实现类
        SubjectTypeHandler handler = subjectTypeHandlerFactory.getHandler(subjectInfo.getSubjectType());
        subjectInfoBO.setId(subjectInfo.getId());
        //对应题目的实现类，调用对应的 插入方法
        handler.add(subjectInfoBO);

        //将题目的 分类id和标签id 插入到 subject_mapping 表。  多对多关系。
        List<Integer> categoryIds = subjectInfoBO.getCategoryIds();
        List<Integer> labelIds = subjectInfoBO.getLabelIds();
        List<SubjectMapping> subjectMappingList=new LinkedList<>();
        categoryIds.forEach(categoryId->{
            labelIds.forEach(labelId->{
                SubjectMapping subjectMapping=new SubjectMapping();
                subjectMapping.setSubjectId(subjectInfo.getId());
                subjectMapping.setCategoryId(Long.valueOf(categoryId));
                subjectMapping.setLabelId(Long.valueOf(labelId));
                subjectMapping.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
                subjectMappingList.add(subjectMapping);
            });
        });
        subjectMappingService.batchInsert(subjectMappingList);

        //同步到es中。构建SubjectInfoEs对象
        SubjectInfoEs subjectInfoEs=new SubjectInfoEs();
        //生成唯一id作为文档id
        subjectInfoEs.setDocId(new IdWorkerUtil(1,1,1).nextId());
        subjectInfoEs.setSubjectId(subjectInfo.getId());
        subjectInfoEs.setSubjectAnswer(subjectInfoBO.getSubjectAnswer());
        subjectInfoEs.setCreateTime(new Date().getTime());
        subjectInfoEs.setSubjectType(subjectInfo.getSubjectType());
        subjectInfoEs.setSubjectName(subjectInfo.getSubjectName());
        // todo 这里的上下文loginId先写死
        subjectInfoEs.setCreateUser("立于浮华");
        subjectEsService.insert(subjectInfoEs);

        //redis放入zadd计入排行榜。 redis中存的是key下面的  loginId和分数
        redisUtil.addScore(RANK_KEY, LoginUtil.getLoginId("loginId"), 1);
        return true;
    }


    /**
     * 分页查询题目列表
     *
     * @param subjectInfoBO
     * @return {@link PageResult}<{@link SubjectInfoBO}>
     */
    @Override
    public PageResult<SubjectInfoBO> getSubjectPage(SubjectInfoBO subjectInfoBO) {
        PageResult<SubjectInfoBO> pageResult=new PageResult<>();
        pageResult.setPageNo(subjectInfoBO.getPageNo());
        pageResult.setPageSize(subjectInfoBO.getPageSize());
        //公式，从第几条开始查
        int start=(subjectInfoBO.getPageNo()-1)* subjectInfoBO.getPageSize();
        //这里转换后，只有 subjectDifficult 赋值了，剩下两个id没有。
        SubjectInfo subjectInfo = SubjectInfoConverter.INSTANCE.convertBoToInfo(subjectInfoBO);
        //先查询符合条件的总数
        int count=subjectInfoService.countByCondition(subjectInfo, subjectInfoBO.getCategoryId(), subjectInfoBO.getLabelId());
        if(count==0){
            //没有查到
            return pageResult;//PageResult里的成员属性有默认值
        }
        //查到了,有记录。 开始分页查询。
        List<SubjectInfo> subjectInfoList = subjectInfoService.queryPage(subjectInfo, subjectInfoBO.getCategoryId(), subjectInfoBO.getLabelId(), start, subjectInfoBO.getPageSize());

        //转换
        List<SubjectInfoBO> subjectInfoBOList = SubjectInfoConverter.INSTANCE.convertListInfoToBO(subjectInfoList);
        pageResult.setRecords(subjectInfoBOList);
        pageResult.setTotal(count);



        return pageResult;
    }

    /**
     * 获取题目信息
     */
    @Override
    public SubjectInfoBO querySubjectInfo(SubjectInfoBO subjectInfoBO) {
        SubjectInfo subjectInfo = subjectInfoService.queryById(subjectInfoBO.getId());
        //这里判断题目的类型.
        //使用工厂+策略模式

        //根据 subjectType 来获取对应 的  SubjectTypeHandler实现类
        SubjectTypeHandler handler = subjectTypeHandlerFactory.getHandler(subjectInfo.getSubjectType());
        //获取题目的答案 或者 选项
        SubjectOptionBO subjectOptionBO = handler.query(subjectInfo.getId());
        //转换 赋值。 将subjectOptionBO 和 subjectInfo 全都赋值给 SubjectInfoBO
        SubjectInfoBO bo = SubjectInfoConverter.INSTANCE.convertOptionAndInfoToBo(subjectOptionBO, subjectInfo);

        //最后还剩下 labelName 查询
        SubjectMapping subjectMapping=new SubjectMapping();
        subjectMapping.setSubjectId(subjectInfo.getId());
        subjectMapping.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        //获取全部的 labelId
        List<SubjectMapping> subjectMappingList = subjectMappingService.queryLabelId(subjectMapping);
        List<Long> labelIdList = subjectMappingList.stream().map(s -> s.getLabelId()).collect(Collectors.toList());
        //查询名字
        List<SubjectLabel> subjectLabels = subjectLabelService.batchQueryById(labelIdList);
        List<String> labelNames = subjectLabels.stream().map(s -> s.getLabelName()).collect(Collectors.toList());
        bo.setLabelName(labelNames);

        //当前用户是否点赞
        bo.setLiked(subjectLikedDomainService.isLiked(subjectInfoBO.getId().toString(),LoginUtil.getLoginId("loginId")));
        //题目的点赞总数
        bo.setLikedCount(subjectLikedDomainService.getLikedCount(subjectInfoBO.getId().toString()));

        //查询出上一题和下一题
        getLastAndNextSubject(subjectInfoBO,bo);

        return bo;
    }

    /**
     * 提取方法：
     *    查询出上一题和下一题
     */
    private void getLastAndNextSubject(SubjectInfoBO subjectInfoBO, SubjectInfoBO bo) {
        //获取这道题的信息
        Long categoryId = subjectInfoBO.getCategoryId();
        Long labelId = subjectInfoBO.getLabelId();
        Long subjectId = subjectInfoBO.getId();

        if (Objects.isNull(categoryId) || Objects.isNull(labelId)) {
            return;
        }
        //根据这道题的信息查询出上一题和下一题。1位下一题，0为上一题。
        Long nextSubjectId = subjectInfoService.getLastAndNextSubject(subjectId, categoryId, labelId, 1);
        bo.setNextSubjectId(nextSubjectId);
        Long lastSubjectId = subjectInfoService.getLastAndNextSubject(subjectId, categoryId, labelId, 0);
        bo.setLastSubjectId(lastSubjectId);
    }

    /**
     * 全文检索
     */
    @Override
    public PageResult<SubjectInfoEs> getSubjectPageBySearch(SubjectInfoBO subjectInfoBO) {
        // 构建 SubjectInfoEs 对象
        SubjectInfoEs subjectInfoEs=new SubjectInfoEs();
        subjectInfoEs.setPageNo(subjectInfoBO.getPageNo());
        subjectInfoEs.setPageSize(subjectInfoBO.getPageSize());
        subjectInfoEs.setKeyWord(subjectInfoBO.getKeyWord());

        return subjectEsService.querySubjectList(subjectInfoEs);
    }

    /**
     * 获取题目贡献榜
     */
    @Override
    public List<SubjectInfoBO> getContributeList() {
        //从reids中查询出来。redis中存的是key下面的  loginId和分数
        Set<ZSetOperations.TypedTuple<String>> typedTuples = redisUtil.rankWithScore(RANK_KEY, 0, 5);
        if (log.isInfoEnabled()) {
            log.info("getContributeList.typedTuples:{}", JSON.toJSONString(typedTuples));
        }
        if (CollectionUtils.isEmpty(typedTuples)){
            return Collections.emptyList();
        }
        List<SubjectInfoBO> boList=new ArrayList<>();
        for (ZSetOperations.TypedTuple<String> rank : typedTuples) {
            SubjectInfoBO bo=new SubjectInfoBO();
            //因为是每增加一题得一分，那么分数刚好就对应了题目数
            bo.setSubjectCount(rank.getScore().intValue());
            //远程调用，获取用户信息
            UserInfo userInfo = userRpc.getUserInfo(rank.getValue());
            bo.setCreateUser(userInfo.getNickName());
            bo.setCreateUserAvatar(userInfo.getAvatar());
            boList.add(bo);
        }
        return boList;
    }
}
